import * as user from '@/api/user';
import * as types from '../action-types';
import { setLocal, getLocal } from '@/utils/local';
import router from '@/router'
import per from '@/router/per.js'
const filterRouter = (authList)=>{//过滤路由的方法
  //conosle.log(authList)//后端返回的数据中auth属性是进行权限鉴定的 
    let auths = authList.map(auth=>auth.auth);//获取到auths的名称进行筛选
    function filter(routes){
        return routes.filter(route=>{
            if(auths.includes(route.meta.auth)){//auths匹配上的就会有相对应的菜单
                if(route.children){//如果有娃儿的话就继续匹配
                    route.children = filter(route.children )
                }
                return route;
            }
        })
    }
    return filter(per)
}
export default {
    state: {
        userInfo: {}, // 用户信息
        hasPermission: false, // 代表用户权限
        menuPermission:false,//代表着菜单权限
    },
    mutations: {
//...
        [types.SET_MENU_PERMISSION](state, has) {
            state.menuPermission = has;
        }
    },
    actions: {
      //...
        async [types.ADD_ROUTE]({commit,state}){
            // 后端返回的用户的权限
            let authList = state.userInfo.authList; 
            //console.log(authList,per)//authList代表着后端返回的数据，per是前端设置的路径
            if(authList){ // 通过权限过滤出当前用户的路由--不同的用户有不同的菜单
                let routes = filterRouter(authList); 
                // 找到manager路由作为第一级 如/manager/articleManager.vue
               //在路由的配置信息上进行查找 --- manager这一条
                let route = router.options.routes.find(item=>item.path === '/manager');
                route.children = routes; // 给manager添加儿子路由
                router.addRoutes([route]); // 动态添加进去
                commit(types.SET_MENU_PERMISSION,true); // 权限设置完毕
            }else{
                commit(types.SET_MENU_PERMISSION,true); // 权限设置完毕
            }
        }
    }
}